package com.bitdf.txing.group.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.interceptor.LoginInterceptor;
import com.bitdf.txing.common.to.UserTo;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.vo.UserInfoVo;
import com.bitdf.txing.group.entity.GroupMemberEntity;
import com.bitdf.txing.group.feign.EsFeignService;
import com.bitdf.txing.group.feign.UserFeignService;
import com.bitdf.txing.group.service.GroupMemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;




/**
 * 
 *
 * @author Lizhiwei
 * @email 123@qq.com
 * @date 2022-09-05 16:02:12
 */
@RestController
@RequestMapping("${txing.request.path.group}/member")
public class GroupMemberController {
    @Autowired
    private GroupMemberService groupMemberService;
    @Autowired
    private UserFeignService userFeign;
    @Autowired
    EsFeignService esFeignService;

    /**
     * param: groupId
     * 查询组团成员
     */
//    @RequestMapping("/list")
//    public R list(@RequestParam Map<String, Object> params){
//        if(!params.containsKey("groupId")){
//            return R.error(TxCodeEnume.SUBMIT_DATA_EXCEPTION.getCode(), TxCodeEnume.SUBMIT_DATA_EXCEPTION.getMsg());
//        }
//        PageUtils page = groupMemberService.queryPage(params);
//        return R.ok().put("page", page);
//    }

    /**
     * 通过组团id查询该组团活动成员详细信息
     * @param id
     * @return
     */
    @GetMapping("/listByGid/{id}")
    public R listByGid(@PathVariable("id") Long id){
        List<GroupMemberEntity> list = groupMemberService.list(new QueryWrapper<GroupMemberEntity>().eq("group_id", id));
        //获取所有成员id的集合
        List<Long> collect = list.stream().map((item) -> {
            return item.getUserId();
        }).collect(Collectors.toList());
        //远程调用tx-user服务查询用户详细信息
        R list1 = userFeign.getByUserList(collect);
        List<UserInfoVo> data = list1.getData("data",new TypeReference<List<UserInfoVo>>() {
        });
        return R.ok().put("data", data);
    }


    /**
     * 通过组团id获取所有成员id集合
     * @param groupId
     * @return
     */
    @GetMapping("/get")
    public R getMemberIdsByGroupId(@RequestParam("groupId") Long groupId){
        List<Long> collect = groupMemberService.getMemberIdsByGroupId(groupId);
        return R.ok().put("data", collect);
    }


    /**
     * 活动新增成员
     * @param groupId
     * @param userId
     * @return
     */
    @GetMapping("/save")
    @Transactional
    @SaCheckLogin
    public R addGroupMember(@RequestParam("groupId") Long groupId,@RequestParam("userId") Long userId){
        boolean b = groupMemberService.addMember(groupId, userId);
        return R.ok();
    }

    /**
     * 修改活动成员项目负责人身份
     */
//    @RequestMapping("/update")
//    public R update(@RequestBody GroupMemberEntity groupMember){
//		groupMemberService.updateById(groupMember);
//        return R.ok();
//    }

    /**
     *  移除某组团中某项目成员 可用剔除成员 或者 自愿申请退出团队
     *  ToDo 如果该项目仅剩最后一人，则无法删除
     */
    @SaCheckLogin
    @RequestMapping("/delete")
    public R delete(@RequestParam("userId") Long userId,@RequestParam("groupId") Long groupId){
        //判定当前登录用户是否为该组团的负责人，如果不是，则无权限完成此操作
        UserTo userTo = LoginInterceptor.threadLocal.get();

        GroupMemberEntity one = groupMemberService.getOne(new QueryWrapper<GroupMemberEntity>()
                .eq("user_id", userTo.getId())
                .eq("group_id", groupId));
        if (one==null){
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION);
        }
        //当是用户自愿退出并且本人是负责人时，不予以退出，否则可以完成操作
        if(userId.equals(userTo.getId())  && one.getLeaderStatus()==1){
            return R.error(TxCodeEnume.CONDITION_NOT_VALID_EXCEPTION.getCode(), TxCodeEnume.CONDITION_NOT_VALID_EXCEPTION.getMsg());
        }
        //当剔除别人，自己不是负责人，没有权限
        if(one.getLeaderStatus()!=1 && !userTo.getId().equals(userId)){
            return R.error(TxCodeEnume.USER_NOT_PERM_EXCEPTION);
        }
        boolean flag=groupMemberService.deleteByUserIdAndGroupId(userId,groupId);
        if (flag){
            return R.ok();
        }else {
           return  R.error("删除失败");
        }
    }

    /**
     * 获取某用户的群及用户信息
     * @param userId
     * @return
     */
    @SaCheckLogin
    @GetMapping("/group/user/get")
    public R getGroupAndUserIdsByUserId(@RequestParam("userId") Long userId){
        Map<Long, List<Long>> listMap = groupMemberService.getGroupAndUserIdsByUserId(userId);
        return R.ok().put("data", listMap);
    }

}
